package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Autowired
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1 参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 文章标题模糊查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //没加""为空判断,测试注意json传参类型
        // 频道id
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        // 文章状态
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        // 发布时间 >= 开始时间 //TODO 有bug？
        if (dto.getBeginPubDate() != null) {
            wrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        // 发布时间 <= 开始时间
        wrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        // 当前自媒体人文章
        WmUser user = WmThreadLocalUtils.getUser();
        System.out.println("user = " + user);
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3 执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //4 返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setData(pageResult.getRecords());
        // 处理文章图片
        result.setHost(webSite);
        return result;
    }


    /**
     * 自媒体文章发布
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //参数校验,content文本内容 集合：type+value
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存或修改文章
        WmNews wmNews = new WmNews();
        //将dto前端传来的参数赋值
        try {
            //注意导的是Spring框架的BeanUtils，不然会失败（为null）
            BeanUtils.copyProperties(dto, wmNews);
        } catch (Exception e) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, e.getMessage());
        }
        //如果文章布局是自动(-1)，需要设置为null,因为是-1，所以不能直接赋值
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        // 处理dto参数 images封面集合 转换成 字符串
        String images = imageListToStr(dto.getImages(), webSite);
        wmNews.setImages(images);
        wmNews.setUserId(user.getId());

        saveWmNews(wmNews);

        //如果是草稿，直接返回
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }
        // 3. 保存文章内容 封面  和素材的关联关系
        // 3.1 抽取文章中关联的图片路径
        List<String> materialUrlList = parseContentImages(dto.getContent());
        // 3.2 关联文章内容中的图片和素材关系
        if (!CollectionUtils.isEmpty(materialUrlList)) {
            saveRelativeInfoForContent(materialUrlList, wmNews);
        }
        // 3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoForCover(materialUrlList, wmNews, dto);

        //3.4 发送待审核消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        return ResponseResult.okResult();

    }

    /**
     * 根据文章id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 自媒体文章-上架、下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);

        //上下架发送消息
        if(wmNews.getArticleId()!=null){
            if (WemediaConstants.WM_NEWS_UP.equals(dto.getEnable())) {
                // 上架
                rabbitTemplate.convertAndSend(
                        NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                        wmNews.getArticleId()
                );
                log.info(" 文章上架消息  成功发送  文章id:{}",wmNews.getArticleId());
            }else {
                // 下架
                rabbitTemplate.convertAndSend(
                        NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                        wmNews.getArticleId()
                );
                log.info(" 文章下架消息  成功发送  文章id:{}",wmNews.getArticleId());
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据id删除自媒体文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        if (WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus()) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH, "需要下架文章");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 查询文章列表和作者（自媒体）
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findListAndName(NewsAuthDTO dto) {
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        Integer currentPage = dto.getPage();
        Integer size = dto.getSize();
        dto.setPage((currentPage-1)*size);
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, listAndPage);
        result.setHost(webSite);
        return result;
    }

    /**
     * 人工审核
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //  通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 保存 封面和素材的关联关系
     *
     * @param materialUrlList
     * @param wmNews
     */
    private void saveRelativeInfoForCover(List<String> materialUrlList, WmNews wmNews, WmNewsDTO dto) {
        // 原本的封面集合列表
        List<String> images = dto.getImages();
        // 判断类型是否为-1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            // 需要自动生成封面
            int size = materialUrlList.size();
            // 如果 size 数量大于0 小于等于2  设置为单图  ， 截取素材url集合中的 1个作为封面
            if (size > 0 && size <= 2) {
                images = materialUrlList.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (size > 2) {
                // 如果 size 数量大于2  设置为多图  ， 截取素材url集合中的 3个作为封面
                images = materialUrlList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                // 设置为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            // 如果有封面图 将图片集合转为字符串设置到wmNews.images 属性中
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(imageListToStr(images, webSite));
            }
            // 修改wmNews
            updateById(wmNews);
        }
        // 如果不为空 保存关联关系
        if (!CollectionUtils.isEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews, WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     * 保存 封面和素材的关联关系
     *
     * @param materialUrlList
     * @param wmNews
     */
    private void saveRelativeInfoForContent(List<String> materialUrlList, WmNews wmNews) {
        saveRelativeInfo(materialUrlList, wmNews, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存关联关系
     *
     * @param materialUrlList
     * @param wmNews
     * @param type
     */
    private void saveRelativeInfo(List<String> materialUrlList, WmNews wmNews, Short type) {
        // 1. 根据url路径列表 查询对应的id
//        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
//                .in(WmMaterial::getUrl, materialUrlList)
//                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
//                // 只返回id字段的值
//                .select(WmMaterial::getId));
        //使用mybatis-plus进行批量查询和插入性能消耗比较大，改用mybatis的动态sql
        //素材ID集合
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrlList, WmThreadLocalUtils.getUser().getId());
        // 2. 判断是否缺失素材
        if (CollectionUtils.isEmpty(ids) || ids.size() < materialUrlList.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "引用的素材不存在");
        }
        // 3. 根据素材id集合 文章id  引用类型 保存关联关系
//        for (WmMaterial wmMaterial : wmMaterials) {
//            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
//            wmNewsMaterial.setMaterialId(wmMaterial.getId());
//            wmNewsMaterial.setNewsId(wmNews.getId());
//            wmNewsMaterial.setType(type);
//            wmNewsMaterialMapper.insert(wmNewsMaterial);
//        }
        wmNewsMaterialMapper.saveRelations(ids, wmNews.getId(), type);

    }

    /**
     * 抽取文章内容中 所引用的所有图片
     *
     * @param content 文章内容
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> contents = JSON.parseArray(content, Map.class);
        return contents.stream()
                // 过滤type=image所有的集合
                .filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                // 获取到image下的value  图片url
                .map(x -> (String) x.get("value"))
                // 图片url去除前缀
                .map(url -> url.replace(webSite, "").replace(" ", ""))
                // 去除重复的路径
                .distinct()
                // stream 转成list集合
                .collect(Collectors.toList());
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews 文章对象（前端传递）
     */
    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); // 上架
        if (wmNews.getId() == null) { // 保存操作
            save(wmNews);
        } else {  // 修改
            // 当前文章 和 素材关系表数据删除,后面再设置关联
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }

    }

    /**
     * 图片列表转字符串，并去除图片前缀
     * @param images  图片列表
     * @param webSite 图片前缀
     */
    private String imageListToStr(List<String> images, String webSite) {
        //将前端的url前缀裁切，再以，号拼接获取成字符串
        //即：https://leadnews-cxh.oss-cn-shanghai.aliyuncs.com/material/a.jpg
        //裁切为：material/a.jpg,XXXX.jpg
        return images.stream().map((url) ->
                url.replace(webSite, "")
        ).collect(Collectors.joining(","));
    }
}
